package com.baymx.anotherapp

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import androidx.collection.ArraySet
import androidx.core.os.bundleOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class FocusService : Service() ,CoroutineScope by MainScope() {

    /** Keeps track of all current registered clients.  */
    private val mClients = ArraySet<Messenger>()
    private val messageHandler = Handler(Looper.getMainLooper()) { m ->
        println("service <-- $m")
        println("service <-- $mClients")
        if (m.what == 0) {
            mClients.add(m.replyTo)
        }
        if (m.what == -1) {
            mClients.remove(m.replyTo)
        }
        if (m.what == 1) {
            m.replyTo.send(Message.obtain(null, 2, 0, 0).apply {
                data = bundleOf("data" to "2")
            })
        }
        if (m.what == 2) {
            launch {
                delay(2000)
                val ite = mClients.iterator()
                while (ite.hasNext()){
                    val item =  ite.next()
                    runCatching {
                        item.send(Message.obtain(null, 2, 0, 0).apply {
                            data = bundleOf("data" to "1")
                        })
                    }.onFailure {
                        ite.remove()
                    }
                }

            }

        }

        true
    }
    private val messager by lazy { Messenger(messageHandler) }
    val id = createNotificationId()

    override fun onCreate() {
        super.onCreate()
        println("FocusService onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        println("FocusService onStartCommand $intent")
        startForeground(id, buildNotification {
            setAutoCancel(true)
                .setContentTitle("message")
                .setVibrate(null)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
        })
        launch {
            delay(3000)
            messageHandler.sendEmptyMessage(1)
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return messager.binder
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }
}